package com.joven.infra.common.model;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.util.Assert;

/**
 * 公共响应对象
 *
 * @author Joven
 * @date 2022/1/6 18:25
 */
@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Response<T> {
    /**
     * 请求成功
     */
    private static final Integer SUCCESS = 200;

    private static final String SUCCESS_MSG = "success";
    /**
     * 请求失败
     */
    private static final Integer FAILED = 400;

    /**
     * 请求未授权
     */
    private static final Integer UNAUTHORIZED = 401;

    private static final String UNAUTHORIZED_MSG = "unauthorized";

    /**
     * 参数非法
     */
    private static final Integer ILLEGAL_ARGUMENT = 402;

    private static final String ILLEGAL_ARGUMENT_MSG = "illegalArgument";
    /**
     * 服务器内部异常
     */
    private static final Integer EXCEPTION = 500;

    private static final String EXCEPTION_MSG = "server internal exception";

    /**
     * 状态码
     */
    private Integer code;
    /**
     * 错误说明
     */
    private String message;
    /**
     * 业务数据
     */
    private T data;

    public static <T> Response<T> success(T data) {
        return Response.<T>builder().code(SUCCESS).message(SUCCESS_MSG).data(data).build();
    }

    public static <T> Response<T> failed(String msg) {
        return Response.<T>builder().code(FAILED).message(msg).build();
    }

    public static <T> Response<T> unauthorized() {
        return Response.<T>builder().code(UNAUTHORIZED).message(UNAUTHORIZED_MSG).build();
    }

    public static <T> Response<T> illegalArgument(String msg) {
        return Response.<T>builder().code(ILLEGAL_ARGUMENT).message(msg).build();
    }

    public static <T> Response<T> exception() {
        return Response.<T>builder().code(EXCEPTION).message(EXCEPTION_MSG).build();
    }

    /**
     * 校验调用是否成功，失败则抛异常
     */
    public void checkResult() {
        Assert.isTrue(this.code.equals(SUCCESS), message);
    }
}
